package com.cg.config;

import com.cg.config.jwt.JwtAuthTokenFilter;
import com.cg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserService userService;
    // 1、指定密码加密方式  效果同  MyPasswordEncoder类
    @Bean
    @SuppressWarnings("deprecation")
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
//        return new BCryptPasswordEncoder();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    // 2、配置用户及其对应的角色
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
        /*auth.inMemoryAuthentication()
                .withUser("root").password("123").roles("ADMIN","DBA").and()
                .withUser("admin").password("123").roles("ADMIN","USER");*/
    }


    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()  // 开启 HttpSecurity 配置
                .antMatchers("/login").anonymous()
                .antMatchers("/admin/**","/product/**").hasRole("admin")  // admin/** 模式URL必须具备ADMIN角色
                .antMatchers("/user/**").access("hasAnyRole('admin','USER')") // 该模式需要ADMIN或者USER角色
                .anyRequest().authenticated() // 用户访问其他URL都必须认证后访问（登录后访问）
//                .and().formLogin().loginProcessingUrl("/login").permitAll() // 开启表单登录并配置登录接口
                .and().csrf().disable();//关闭csrf
        http.addFilterBefore(jwtAuthTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Autowired
    private JwtAuthTokenFilter jwtAuthTokenFilter;
}
